﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SharpSvn;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace SvnToTfs
{
  public class SvnHelper
  {
    #region Private variables

    private string _subversionUrl;
    private string _subversionRelativeUrl;
    private Regex _extractRelative = new Regex("(.*/Trunk|trunk/)(.*)");

    #endregion

    #region Constructors

    public SvnHelper(string subversionUrl)
    {
      _subversionUrl = subversionUrl;

      // Get the relative Path to the SVN repository the user requested
      string urlRelative = _extractRelative.Replace(subversionUrl, "$2");
      _subversionRelativeUrl = urlRelative.EndsWith("/") ? urlRelative : urlRelative + "/";

    }


    /// <summary>
    /// Check if the item URL is part of the subversion repository
    /// url
    /// </summary>
    /// <param name="itemAbsoluteUrl"></param>
    /// <returns></returns>
    public bool ValidateItemAgainstUrl(string itemAbsoluteUrl)
    {
      // Extract the trunk from the changePath
      string itemRelative = _extractRelative.Replace(itemAbsoluteUrl, "$2");

      //Now check if the ChangeItem match the portion of the SVN we're interested in
      return Regex.IsMatch(itemRelative, string.Format("{0}(.*)", SubversionRelativeUrl));
    }

    /// <summary>
    /// Convert a absolute URL to a local URL
    /// </summary>
    /// <param name="itemAbsoluteUrl"></param>
    /// <returns></returns>
    public string ConvertUrlToLocal(string itemAbsoluteUrl)
    {
      string itemRelative = _extractRelative.Replace(itemAbsoluteUrl, "$2");

      Regex convertLocal = new Regex(string.Format("{0}(.*)", SubversionRelativeUrl));
      return convertLocal.Replace(itemRelative, "$1");
    }

    #endregion

    #region Properties

    public string SubversionUrl
    {
      get
      {
        return _subversionUrl;
      }
      set
      {
        _subversionUrl = value;
      }
    }

    public string SubversionRelativeUrl
    {
      get
      {
        return _subversionRelativeUrl;
      }
      set
      {
        _subversionRelativeUrl = value;
      }
    }

    #endregion

    #region Public methods

    #endregion
  }
}
